package com.whately.core.base.config.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Interceptor拦截器切面
 * 放过所以的pre 请求，preflight request
 */
@Aspect
@Component
public class PreRequestAspect {

    private final static Logger logger = LoggerFactory.getLogger(PreRequestAspect.class);

    // 拦截所有的实现了接口org.springframework.web.servlet.HandlerInterceptor，所有preHandle方法
    @Pointcut("execution( * org.springframework.web.servlet.HandlerInterceptor.preHandle(..))")
    public void cut() {
    }

    @Around(value = "cut()")
    public Object processTx(ProceedingJoinPoint jp) throws Throwable {
        HttpServletRequest request = (HttpServletRequest) jp.getArgs()[0];
        if (request != null && CorsUtils.isPreFlightRequest(request)) {
            return true;
        } else {
            return jp.proceed();
        }
    }

}
